home *** CD-ROM | disk | FTP | other *** search
/ Chip 2005 June / ccd0605.iso / Software / Shareware / Programare / nativej / nativej-trial.exe / {app} / examples-source / Service.java < prev    next >
Text File  |  2004-12-14  |  2KB  |  68 lines

  1. package examples;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. /**
  7.  * This is a sample Java program that runs as a service.
  8.  *
  9.  * It appends the current date/time to a file called "service.log" at 5 secs interval
  10.  * until it is stopped.
  11.  *
  12.  * The "stop" command only works when used with NativeJ-generated executables.
  13.  * That's because NativeJ will create a separate thread within the same JVM space
  14.  * which will called main() with the "stop" parameter. It does not work when executed
  15.  * from the command line, since that will cause it to execute in separate JVM space.
  16.  *
  17.  * Take a look at Service2.java to find out how to implement the "stop" command that
  18.  * will work with BOTH the command line and NativeJ-generated executables.
  19.  */
  20. public class Service
  21. {
  22.     /**
  23.      * The main() function accepts one single parameter: "start" or "stop".
  24.      * The first parameter starts the date/time logging service, while the
  25.      * second parameter stops the service.
  26.      */
  27.     static boolean stop = false;
  28.     public static void main(String[] args) throws Exception
  29.     {
  30.         // Start the service
  31.         if (args[0].equals("-start"))
  32.         {
  33.             while(true)
  34.             {
  35.                 // Append current date/time to log file
  36.                 log("Current date/time is " + new Date());
  37.  
  38.                 // Sleep for 5 secs
  39.                 Thread.currentThread().sleep(5000);
  40.  
  41.                 // Check for termination
  42.                 if (stop)
  43.                 {
  44.                     log("Service stopped.");
  45.                     break;
  46.                 }
  47.             }
  48.         }
  49.         else
  50.         // Stop the service
  51.         if (args[0].equals("-stop"))
  52.         {
  53.             // Set the termination flag
  54.             stop = true;
  55.         }
  56.     }
  57.  
  58.     /**
  59.      * Log given string to file "service.log".
  60.      */
  61.     static void log(String msg) throws IOException
  62.     {
  63.         PrintWriter pw = new PrintWriter(new FileWriter("service.log", true));
  64.         pw.println(msg);
  65.         pw.close();
  66.     }
  67. }
  68.